package com.example.demo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import com.example.demo.util.R;

@ControllerAdvice
public class GlobalExceptionHandler {

  @Value("${spring.servlet.multipart.max-file-size}")
  private String maxSize;

  /**
   * 全局处理异常
   * 
   * @param e
   * @return R
   */
  @ExceptionHandler(Exception.class)
  @ResponseBody
  public R globalExceptionHandler(Exception e) {
    e.printStackTrace();

    return R.serveError();
  }

  /**
   * 处理自定义异常
   * @ExceptionHandler(自定义异常类).
   * public R globalExceptionHandler(自定义异常类 e) {
   * e.printStackTrace();
   *
   * return R.serveError();
   * }
   */

  /**
   * 文件上传异常
   * 
   * @param e
   * @return
   */
  @ExceptionHandler(MaxUploadSizeExceededException.class)
  @ResponseBody
  public R maxUploadSizeExceededExceptionHandler(MaxUploadSizeExceededException e) {
    e.printStackTrace();

    return R.fail("文件大小超出限制:" + maxSize);
  }

}
